<?php

namespace app\api\controller;

use app\api\model\Wxapp as WxappModel;
use app\common\library\wechat\WxPay;
use app\common\model\Enum;
use think\facade\Validate;
use think\Db;
use think\facade\Log;
use app\api\model\HttpMachine;

/**
 * 用户订单管理
 * Class Order
 * @package app\api\controller\user
 */
class Order extends Controller
{
    /* @var \app\api\model\User $user */
    private $user;

    /**
     * 构造方法
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 扫码支付生成订单给小程序支付
     * @param $order_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function scanpay()
    {
        $post = $this->request->post();
        $openid=$post["openid"];
        $unionid=$post["unionid"];
        $uid=$post["uid"];
        $machineNo=$post["machineno"];
        $action=$post["action"];

        $re = HttpMachine::GetMachineWorkStatus($machineNo);
        if($re == ""){
            return $this->renderError("execute command fail");
        }
        if($re != "1"){
            return $this->renderError("please change one");
        }

        $machine = Db::table('machine')->where("machine_no",$machineNo)->find();
        if(!$machine){
            return $this->renderError("machine not exist");
        }

        $wint = Enum::GetWashInt($action);
        if($wint == -1){
            return $this->renderError("error command");
        }

        $amount=0;
        $map=[
            ['wash_type', '=', $wint],
            ['area_id', '=', $machine['area_id']]
        ];
        $price = Db::table('price')->where($map)->find();
        if(!$price){
            return $this->renderError("price is empty");
        }
        $amount=$price["wash_price"]*100;

        $user = Db::table('user')->where("id",$uid)->find();
        if(!$user){
            return $this->renderError("user is empty");
        }

        $no = Enum::orderNo(Enum::order_type_scan);
        $time =date('Y-m-d H:i:s',time());
        

        $data=[
            'user_id' => $user['id'],
            'apsid' => $user['apsid'],
            'open_id' => $openid,
            'union_id' => $unionid,
            'order_no' => $no,
            'create_at' => $time,
            'update_at' => $time,
            'trade_no' => "",
            'card_no' => "",
            'machine_no' => $machineNo,
            'type' => Enum::b_type_scan,
            'area_id' => $machine['area_id'],
            'amount' => $amount,
            'wash_type' => $action,
            'pay_status' => Enum::PAY_WAIT,
            'pay_channel' => 0
        ];
 
        //插入数据
        $id=Db::table('order')->insertGetId($data);
        //echo Db::table('charge')->getLastSql();
        // return $this->renderSuccess($id);
        
        // 发起微信支付
        $WxPay = new WxPay(Enum::wxconfig);
        $wxParams = $WxPay->unifiedorder($no, $openid, $amount/100,"扫码洗衣");
        $wxParams['appId'] =Enum::wxconfig['app_id'];
        return $this->renderSuccess($wxParams);
       
    }

    /**
     * 充值
     * @param $post
     * @return array
     */
    public function docharge()
    {
        $post = $this->request->post();
        $uid=$post["uid"];
        $openid=$post["openid"];
        $unionid=$post["unionid"];
        $apsid=$post["apsid"];
        $amount=$post["amount"];
        $gift=$post["gift"];

        //Log::write('$docharge amount- '.$amount);
        
        if(!Validate::must($amount)){
            return $this->renderError("充值金额不能为空");
        }
        
        //
        $amount=$amount*100;
        $amount=(int)$amount;

        $gift=$gift*100;
        $gift=(int)$gift;

        if(!Validate::between($amount,"100,100000")){
            return $this->renderError("充值金额太大或太小");
        }
        $no = Enum::orderNo(Enum::order_type_wxcz);
        $time =date('Y-m-d H:i:s',time());

        $data=[
            'user_id' => $uid,
            'open_id' => $openid,
            'union_id' => $unionid,
            'type' => Enum::b_type_wxcz,
            'trade_no' => "",
            'card_no' => "",
            'order_no' => $no,
            'apsid' => $apsid,
            'pay_status' => Enum::PAY_WAIT,
            'create_at' => $time,
            'update_at' => $time,
            'czamount' => $amount,
            'amount' => $amount + $gift,
            'gift' => $gift
        ];

        //插入数据
        $id=Db::table('charge')->insertGetId($data);
        // return $this->renderSuccess($id);
        
        // 发起微信支付
        $WxPay = new WxPay(Enum::wxconfig);
        $wxParams = $WxPay->unifiedorder($no, $openid, $amount/100,"微信充值");
        $wxParams['appId'] =Enum::wxconfig['app_id'];
        return $this->renderSuccess($wxParams);

    }

    public function notify()
    {
       
        $WxPay = new WxPay(Enum::wxconfig);
        if (!$xml = file_get_contents('php://input')) {
           $WxPay->returnCode(false, 'Not found DATA');
        }
        // 将服务器返回的XML数据转化为数组
        $data = $WxPay->fromXml($xml);

        //Log::write('$notify xml- '.$xml);
        
        // 保存微信服务器返回的签名sign
        $dataSign = $data['sign'];
        // sign不参与签名算法
        unset($data['sign']);
        // 生成签名
        $sign = $WxPay->makeSign($data);
        // 判断签名是否正确  判断支付状态
        if (($sign === $dataSign)  && ($data['return_code'] == 'SUCCESS')  && ($data['result_code'] == 'SUCCESS')) {
           
        }else{
            $WxPay->returnCode(false, '签名失败');
        }
        
        // $data["out_trade_no"]="wxcz2019050598565710";
        // $data["transaction_id"]=intval(time());
        // 发起微信支付
        
        if(!empty($data)){
            $out_trade_no = $data['out_trade_no'];
            
            $WxPay->out_trade_no = $out_trade_no;
            
            $transaction_id = $data['transaction_id'];
            $time = date('Y-m-d H:i:s',time());
            //判断是订单 还是充值
            $type = substr($out_trade_no,0,4);
            if($type == Enum::order_type_scan){ //扫码支付
                $map=[
                    ['order_no', '=', $out_trade_no]
                ];
                $order=Db::table('order')->where($map)->find();
                if(empty($order)){
                    $WxPay->returnCode(false, '订单丢失');
                }

                if($order['pay_status']==Enum::PAY_SUCESS){
                    $WxPay->returnCode(true);
                }

                $user = Db::table('user')->where("id",$order['user_id'])->find();
                if(!$user){
                    $WxPay->returnCode(false, 'user is empty');
                }

                //这里要提前插入充值记录,这里是没有赠送的.
                $no_cz = Enum::orderNo(Enum::order_type_wxcz);
                $data_cz=[
                    'user_id' => $user['id'],
                    'open_id' => $order['open_id'],
                    'union_id' => $order['union_id'],
                    'type' => Enum::b_type_wxcz,
                    'trade_no' =>$transaction_id,//记录订单订单的单号
                    'card_no' => "",
                    'order_no' => $no_cz,
                    'apsid' => $user['apsid'],
                    'pay_status' => Enum::PAY_SUCESS,
                    'create_at' => $time,
                    'update_at' => $time,
                    'czamount' => $order['amount'],
                    'amount' => $order['amount'],
                    'gift' => 0
                ];
                $book_cz=[
                    'user_id' => $user['id'],
                    'b_type' => Enum::b_type_wxcz,
                    'b_id' => 0,
                    'b_no' => $no_cz,
                    'create_at' => $time,
                    'old_amount' =>$user['amount'],
                    'var_amount' =>$order['amount'] ,
                    'amount' => $user['amount'] + $order['amount']
                ];

                $book=[
                    'user_id' => $user['id'],
                    'b_type' => Enum::b_type_scan,
                    'b_id' => $order['id'],
                    'b_no' => $order['order_no'],
                    'create_at' => $time,
                    'old_amount' =>$user['amount'] + $order['amount'],
                    'var_amount' => -1 * $order['amount'],
                    'amount' => $user['amount']
                ];

                Db::startTrans();
                try {
                    //先充值
                    $charge_id=Db::table('charge')->insertGetId($data_cz);
                    $book_cz['b_id'] = $charge_id;
                    Db::table('daybook')->strict(false)->insert($book_cz);

                    //修改订单状态
                    Db::table('order')->where('id',$order['id'])->update([ 'pay_status'=> Enum::PAY_SUCESS, 'update_at' => $time,'trade_no'=>$transaction_id ]);
                    //再消费 这样用户余额不用改动
                    Db::table('daybook')->strict(false)->insert($book);

                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $WxPay->returnCode(false, '数据更新异常'.$e);
                }

                $re=HttpMachine::SendWashCammand($order['machine_no'],$order['wash_type']);
                Db::table('order')->where('id',$order['id'])->update(['wash_status'=> $re ]);

            }else if($type == Enum::order_type_wxcz){//微信充值 ,['pay_status', '=', Enum::PAY_WAIT]

                $map=[
                    ['order_no', '=', $out_trade_no]
                ];
                $charge=Db::table('charge')->where($map)->find();
                if(empty($charge)){
                    $WxPay->returnCode(false, '充值订单丢失');
                }
                if($charge['pay_status']==Enum::PAY_SUCESS){
                    $WxPay->returnCode(true);
                }

                $user = Db::table('user')->where("id",$charge['user_id'])->find();
                if(!$user){
                    $WxPay->returnCode(false, 'user is empty');
                }

                $amount =  $charge['amount'] ; //注意 czamount 与 amount 的差异
                $n_amount = $user['amount'] + $amount;

                $book=[
                    'user_id' => $user['id'],
                    'b_type' => Enum::b_type_wxcz,
                    'b_id' => $charge['id'],
                    'b_no' => $charge['order_no'],
                    'create_at' => $time,
                    'old_amount' =>$user['amount'],
                    'var_amount' =>$amount ,
                    'amount' => $n_amount
                ];

                Db::startTrans();
                try {
                    //修改订单状态
                    Db::table('charge')->where('id',$charge['id'])->update([ 'pay_status'=> Enum::PAY_SUCESS, 'update_at' => $time,'trade_no'=>$transaction_id ]);

                    //用户的钱变化
                    $c = Db::table('user')->where('id',$user['id'])->setInc('amount',$amount);

                    Db::table('daybook')->strict(false)->insert($book);

                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $WxPay->returnCode(false, '数据更新异常'.$e);
                }

            }else{
                $WxPay->returnCode(false, '订单类别异常');
            }
            
            $WxPay->returnCode(true);
        }else{
            // 返回状态
            $WxPay->returnCode(false, '签名失败');
        }
    }

}
